package xin.nick.manager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import xin.nick.entity.Role;
import xin.nick.mapper.RoleMapper;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author Nick
 * @since 2022/8/11
 */
@Component
public class RoleManager {

    @Autowired
    private RoleMapper roleMapper;

    /**
     * 本地缓存的信息,如果是集群的情况需要用分布式缓存进行操作
     */
    private static Map<Long, Role> roleMap = null;
    private static List<Role> roleList = null;


    /**
     * 获取角色列表
     * @return
     */
    public List<Role> getRoleList() {

        if (Objects.nonNull(roleList)) {
            return roleList;
        }

        roleList = roleMapper.selectList(null);
        return roleList;
    }


    /**
     * 获取角色Map
     * @return
     */
    public Map<Long, Role> getRoleMap() {

        if (Objects.nonNull(roleMap)) {
            return roleMap;
        }

        List<Role> roleList = getRoleList();
        roleMap = roleList.stream()
                .filter(Objects::nonNull)
                .filter(role -> Objects.nonNull(role.getRoleId()))
                .collect(Collectors.toMap(Role::getRoleId, Function.identity(), (v1, v2) -> v2));

        return roleMap;
    }

    /**
     * 获取所有角色id列表
     * @return
     */
    public List<Long> getRoleIdList() {
        List<Role> roleList = getRoleList();
        List<Long> roleIdList = roleList.stream()
                .filter(Objects::nonNull)
                .map(Role::getRoleId)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
        return roleIdList;
    }

    /**
     * 获取存在的角色id
     * @param filterRoleIdList
     * @return
     */
    public List<Long> filterExistingIdList(List<Long> filterRoleIdList) {
        if (CollectionUtils.isEmpty(filterRoleIdList)) {
            return new ArrayList<>();
        }

        List<Long> roleIdList = getRoleIdList();
        List<Long> returnList = filterRoleIdList.stream()
                .filter(Objects::nonNull)
                .filter(roleId -> roleIdList.contains(roleId))
                .collect(Collectors.toList());
        return returnList;
    }

}
